package com.xxq.gulimall.product.service.impl;

import com.xxq.common.utils.R;
import com.xxq.gulimall.product.entity.*;
import com.xxq.gulimall.product.es.SkuEsModel;
import com.xxq.gulimall.product.feign.CouponFeignService;
import com.xxq.gulimall.product.feign.WareFeignService;
import com.xxq.gulimall.product.feign.entity.coupon.MemberPriceEntity;
import com.xxq.gulimall.product.feign.entity.coupon.SkuFullReductionEntity;
import com.xxq.gulimall.product.feign.entity.coupon.SkuLadderEntity;
import com.xxq.gulimall.product.feign.entity.coupon.SpuBoundsEntity;
import com.xxq.gulimall.product.service.*;
import com.xxq.gulimall.product.vo.addSpuVo.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxq.common.utils.PageUtils;
import com.xxq.common.utils.Query;

import com.xxq.gulimall.product.dao.SpuInfoDao;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private ProductAttrValueService attrValueService;
    @Resource
    private AttrService attrService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuSaleAttrValueService saleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private CategoryBrandRelationService brandRelationService;
    @Resource
    private BrandService brandService;
    @Resource
    private WareFeignService wareFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCatelogIdAndBrandId(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catelog_id", params.get("catelogId"))
                .eq("brand_id", params.get("brandId"));
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public void saveSpuInfo(AddSpuVo addSpuVo) {
        // 1、保存spu基本信息 spu_info
        Long spuId = saveBaseSpuInfo(addSpuVo);
        // 2、保存spu描述图片 spu_info_desc
        saveSpuDesc(addSpuVo, spuId);
        // 3、保存spu图片集 spu_images
        saveSpuImages(addSpuVo, spuId);
        // 4、保存spu规格参数 product_attr_value
        saveAttrValue(addSpuVo, spuId);
        // 5、保存当前spu对应的sku信息
        // 5.1、sku基本信息 sku_info
        // 5.2、sku图片信息 sku_images
        // 5.3、sku的销售属性 sku_sale_attr_value
        // 5.4、sku的优惠、满减信息 sms-> sku_ladder\sku_full_reduction\member_price
        saveSkuInfo(addSpuVo, spuId);
        // 6、保存spu的积分信息 sms-> spu_bounds 跨库远程保存
        saveSpuBounds(addSpuVo, spuId);
    }

    @Override
    // 20、商品上架
    public void upAttr(Long spuId) {
        List<SkuInfoEntity> skuInfoList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        // brandId、catalogId
        Long brandId;
        Long catalogId;
        if (skuInfoList.size() != 0) {
            brandId = skuInfoList.get(0).getBrandId();
            catalogId = skuInfoList.get(0).getCatalogId();
        }
        else
            return;

        // 查询attrs
        List<ProductAttrValueEntity> attrValueList = attrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIdList = attrValueList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<AttrEntity> attrEntityList = attrService.listByIds(attrIdList);
        List<SkuEsModel.Attr> attrList = attrEntityList
                .stream()
                .map(attrEntity -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            if (attrEntity.getSearchType() == 1) {
                for (ProductAttrValueEntity valueEntity : attrValueList) {
                    if (attrEntity.getAttrId().equals(valueEntity.getAttrId())) {
                        attr.setAttrId(valueEntity.getAttrId());
                        attr.setAttrName(valueEntity.getAttrName());
                        attr.setAttrValue(valueEntity.getAttrValue());
                        break;
                    }
                }
            }

            return attr;
        }).collect(Collectors.toList());


        // brandImg
        BrandEntity brand = brandService.getById(brandId);
        String logo = brand.getLogo();

        // brandName、catelogName
        CategoryBrandRelationEntity relation = brandRelationService.getOne(
                new QueryWrapper<CategoryBrandRelationEntity>()
                .eq("brand_id", brandId)
                .eq("catelog_id", catalogId)
        );
        String brandName = relation.getBrandName();
        String catelogName = relation.getCatelogName();

        // stock
        List<Long> skuIds = skuInfoList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        R stock = stock = wareFeignService.skuStock(skuIds);
        Map<Long, Boolean> map = (Map<Long, Boolean>) stock.get("map");

        // 组装
        List<SkuEsModel> esModelList = skuInfoList.stream().map(entity -> {
            SkuEsModel model = new SkuEsModel();
            model.setSkuId(entity.getSkuId());
            model.setSpuId(spuId);
            model.setSkuPrice(entity.getPrice());
            model.setSkuImg(entity.getSkuDefaultImg());
            model.setSaleCount(entity.getSaleCount());
            model.setHasStock(map.get(entity.getSkuId()));
            model.setHotScore(0L);
            model.setBrandId(brandId);   
            model.setCatelogId(catalogId);
            model.setBrandName(brandName);
            model.setCatelogName(catelogName);
            model.setBrandImg(logo);
            model.setAttrs(attrList);

            return model;
        }).collect(Collectors.toList());
    }

    // 1、保存spu基本信息 spu_info
    private Long saveBaseSpuInfo(AddSpuVo addSpuVo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();

        spuInfoEntity.setSpuName(addSpuVo.getSpuName());
        spuInfoEntity.setSpuDescription(addSpuVo.getSpuDescription());
        spuInfoEntity.setCatelogId(addSpuVo.getCatalogId());
        spuInfoEntity.setBrandId(addSpuVo.getBrandId());
        spuInfoEntity.setWeight(addSpuVo.getWeight());
        spuInfoEntity.setPublishStatus(addSpuVo.getPublishStatus());

        this.save(spuInfoEntity);

        return spuInfoEntity.getId();
    }

    // 2、保存spu描述图片 spu_info_desc
    private void saveSpuDesc(AddSpuVo addSpuVo, Long spuId) {
        List<String> decript = addSpuVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuId);
        descEntity.setDecript(String.join(",", decript));

        spuInfoDescService.save(descEntity);
    }

    // 3、保存spu图片集 spu_images
    private void saveSpuImages(AddSpuVo addSpuVo, Long spuId) {
        List<String> images = addSpuVo.getImages();
        List<SpuImagesEntity> imagesEntities = new ArrayList<>();
        imagesEntities = images.stream().map(img -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setImgUrl(img);

            return spuImagesEntity;
        }).collect(Collectors.toList());

        spuImagesService.saveBatch(imagesEntities);
    }

    // 4、保存spu规格参数 product_attr_value
    private void saveAttrValue(AddSpuVo addSpuVo, Long spuId) {
        List<BaseAttrsVo> baseAttrVos = addSpuVo.getBaseAttrVos();

        List<ProductAttrValueEntity> collect = baseAttrVos.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(spuId);
            valueEntity.setAttrId(attr.getAttrId());
            // TODO 循环连接数据库
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());

            return valueEntity;
        }).collect(Collectors.toList());

        attrValueService.saveBatch(collect);
    }

    // 5.1、sku基本信息 sku_info
    // 5.2、sku图片信息 sku_images
    // 5.3、sku的销售属性 sku_sale_attr_value
    // 5.4、sku的优惠、满减信息 sms-> sku_ladder\sku_full_reduction\member_price
    private void saveSkuInfo(AddSpuVo addSpuVo, Long spuId) {
        List<SkusVo> skusVos = addSpuVo.getSkusVos();

        skusVos.forEach(skusVo -> {
            // 5.1、sku基本信息 sku_info
            SkuInfoEntity skuInfo = new SkuInfoEntity();
            {
                skuInfo.setSpuId(spuId);
                skuInfo.setSkuName(skusVo.getSkuName());
                skuInfo.setPrice(skusVo.getPrice());
                skuInfo.setSkuTitle(skusVo.getSkuTitle());
                skuInfo.setSkuSubtitle(skusVo.getSkuSubtitle());
                skuInfo.setCatalogId(addSpuVo.getCatalogId());
                skuInfo.setBrandId(addSpuVo.getBrandId());
                skuInfo.setSaleCount(skusVo.getFullCount());
                skuInfo.setSkuDesc(String.join(",", skusVo.getDescar()));

                // default_img
                String defaultImg = "";
                for (ImagesVo image : skusVo.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                        break;
                    }
                }
                skuInfo.setSkuDefaultImg(defaultImg);

            }
            skuInfoService.save(skuInfo);

            // 5.2、sku图片信息 sku_images
            List<SkuImagesEntity> imagesEntities;
            {
                imagesEntities = skusVo.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(spuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());

                    return skuImagesEntity;
                }).collect(Collectors.toList());

            }
            skuImagesService.saveBatch(imagesEntities);

            // 5.3、sku的销售属性 sku_sale_attr_value
            List<SkuSaleAttrValueEntity> saleAttrValueEntities;
            {
                saleAttrValueEntities = skusVo.getAttrVo().stream().map(attrVo -> {
                    SkuSaleAttrValueEntity valueEntity = new SkuSaleAttrValueEntity();
                    valueEntity.setSkuId(skuInfo.getSkuId());
                    valueEntity.setAttrId(attrVo.getAttrId());
                    valueEntity.setAttrName(attrVo.getAttrName());
                    valueEntity.setAttrValue(attrVo.getAttrValue());

                    return valueEntity;
                }).collect(Collectors.toList());
            }
            saleAttrValueService.saveBatch(saleAttrValueEntities);

            // 5.4、sku的优惠、满减信息 sms-> sku_ladder\sku_full_reduction\member_price
            SkuLadderEntity skuLadderEntity = new SkuLadderEntity();
            {
                skuLadderEntity.setSkuId(skuInfo.getSkuId());
                skuLadderEntity.setFullCount(skusVo.getFullCount().intValue());
                skuLadderEntity.setDiscount(skusVo.getDiscount());
                skuLadderEntity.setPrice(skusVo.getPrice());
            }
            couponFeignService.skuladderInfo(skuLadderEntity);

            SkuFullReductionEntity skuFullReductionEntity = new SkuFullReductionEntity();
            {
                skuFullReductionEntity.setSkuId(skuInfo.getSkuId());
                skuFullReductionEntity.setFullPrice(skusVo.getFullPrice());
                skuFullReductionEntity.setReducePrice(skusVo.getReducePrice());
            }
            couponFeignService.skufullreductionInfo(skuFullReductionEntity);

            List<MemberPriceEntity> memberPriceEntities;
            {
                memberPriceEntities = skusVo.getMemberPriceVo().stream().map(memberPriceVo -> {
                    MemberPriceEntity memberPriceEntity = new MemberPriceEntity();
                    memberPriceEntity.setSkuId(skuInfo.getSkuId());
                    memberPriceEntity.setMemberLevelId(memberPriceVo.getId());
                    memberPriceEntity.setMemberLevelName(memberPriceVo.getName());
                    memberPriceEntity.setMemberPrice(memberPriceVo.getPrice());

                    return memberPriceEntity;
                }).collect(Collectors.toList());
            }
            couponFeignService.memberpriceInfo(memberPriceEntities);

        });

    }

    // 6、保存spu的积分信息 sms-> spu_bounds 跨库远程保存
    private void saveSpuBounds(AddSpuVo addSpuVo, Long spuId) {
        BoundsVo boundsVo = addSpuVo.getBoundsVo();
        SpuBoundsEntity spuBoundsEntity = new SpuBoundsEntity();
        spuBoundsEntity.setSpuId(spuId);
        spuBoundsEntity.setBuyBounds(boundsVo.getBuyBounds());
        spuBoundsEntity.setGrowBounds(boundsVo.getGrowBounds());
        couponFeignService.spuboundsInfo(spuBoundsEntity);
    }
}